package edu.rutgers.moko;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import edu.rutgers.moko.data.FieldAccess;
import edu.rutgers.moko.data.ProtectedRule;
import edu.rutgers.moko.data.util.FieldAccessUtil;
import edu.rutgers.moko.data.util.Flag;
import edu.rutgers.moko.data.util.OMField;
import edu.rutgers.moko.data.util.PrivacyMode;
import edu.rutgers.moko.data.util.ProtectedAccess;
import edu.rutgers.moko.data.util.SecurityUtil;

public class SequrityControlServlet extends HttpServlet {

	private static final long serialVersionUID = -7100991365098853668L;
	//private final File dir = new File("/home/dashali/Documents/school/projects/server");
	private final File dir = new File("/home/root/server");
	private final File msgs = new File(dir, "properties.txt");
	//rule format: var_name \t 
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		if (SecurityUtil.localAccess(req)) {
			List<String> lines = new ArrayList<String>();
			if (msgs.exists()) {
				lines = FileUtils.readLines(msgs);
			}
			FieldAccessUtil faUtil = new FieldAccessUtil(lines);

			PrintWriter pw = null;
			StringBuilder msg = new StringBuilder();
        
        
        for (OMField prop : OMField.valuesAsList()) {
			FieldAccess fa = new FieldAccess();
			fa.setProp(prop);
			fa.setPrivacyMode(PrivacyMode.getByField(req
						.getParameter("pm_" + prop.field())));
				if (fa.getPrivacyMode().equals(PrivacyMode.PROTECTED)) {
					for (int i = 0; i < faUtil.numberOfRules(prop); i++) {
						ProtectedAccess pam = ProtectedAccess.getByField(req.getParameter("act_" + prop.field() + i));
						ProtectedRule pr = new ProtectedRule(pam);

						pr.setFlag(Flag.getByTitle(req.getParameter("flag_"	+ prop.field() + i)));
						String loc = req.getParameter("loc_" + prop.field() + i);
						String ap = req.getParameter("ap_" + prop.field() + i);
						String cli = req.getParameter("cl_" + prop.field() + i);
						pr.validateAndSetControlValues(loc, ap, cli);
						fa.addProtectedRule(pr);

					}
					
					ProtectedAccess pam = ProtectedAccess.getByField(req.getParameter("act_" + prop.field() + "new"));
					if(pam!=null){
						ProtectedRule pr = new ProtectedRule(pam);
	
						pr.setFlag(Flag.getByTitle(req.getParameter("flag_"	+ prop.field() + "new")));
						String loc = req.getParameter("loc_" + prop.field() + "new");
						String ap = req.getParameter("ap_" + prop.field() + "new");
						String cli = req.getParameter("cl_" + prop.field() + "new");
						pr.validateAndSetControlValues(loc, ap, cli);
						fa.addProtectedRule(pr);
					}
					if (fa.getProtectedRules().size() == 0) {
						fa.setPrivacyMode(PrivacyMode.PRIVATE);
					}
				}
				msg.append(fa.getFieldAccessAsRule());
			}
        
        try {
			pw = new PrintWriter(new FileWriter(msgs.getCanonicalPath(), false), false);
			pw.println(msg.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			pw.close();
		}
		}
        res.sendRedirect("/scs");

	}



	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html; charset=ISO-8859-4");
		PrintWriter out = res.getWriter();
		out.println("<html>");
		out.println("<head><title>OM >> Sequrity Controls</title>" + ServletUtil.showhideJs() + " " + ServletUtil.css()+ "</head>");

		out.println("<body>");
		out.println("<h1>OM >> Sequrity Controls</h1>");
		out.print("<a href=\"/state\">Home</a>");
		out.print(" | <a href=\"/rss\">RSS</a>");
		out.print(" | <a href=\"/msg\">Messages</a>");
		if(SecurityUtil.localAccess(req)){
			out.print(" | <a href=\"/scs\">Adjust sequrity controls</a>");
		}
		
		if(SecurityUtil.localAccess(req)){
		
			List<String> lines = new ArrayList<String>();
			if(msgs.exists()){
	        	lines = FileUtils.readLines(msgs);
			}
			FieldAccessUtil faUtil = new FieldAccessUtil(lines);
			out.println("<br><FORM ACTION=\"/scs\" METHOD=\"POST\" name=\"propertyform\">");
		    out.println("<table class=\"border\">" +
		    		"<thead><tr><th>Property Name</th><th>Privacy Mode</th><th>&nbsp;</th></tr></thead>");
		    for (OMField prop : OMField.valuesAsList()) {
				out.println("<tr><th>" + prop.title() + "</th><td valign=\"top\">");
				//Privacy Mode
				out.print("<select name=\"pm_"+ prop.field() +"\" id=\"pm_"+ prop.field() +"\" onChange=\"showhide('pm_"+ prop.field() +"','"+prop.field()+"newdiv')\">");
				for (PrivacyMode pm : PrivacyMode.valuesAsList()) {
					out.print("<option value=\""+pm.name()+"\" "+faUtil.privacyModelSelected(prop, pm) +">"+pm.modelName()+"</option>");
				}
				out.println("</select></td><td colspan=\"2\"></td></tr>");
				
				HashMap<Integer, ProtectedRule> rules = faUtil.propProtectedRules(prop);
				Integer counter;
				out.print("<tbody id=\""+prop.field()+"newdiv\" style=\"display:");
				if (!PrivacyMode.PROTECTED.equals(faUtil
						.propertyPrivacyMode(prop))) {
					out.print("none");
				}
				 
				out.print(";\">");
				for (Integer i : rules.keySet()) {
					ProtectedRule pr = rules.get(i);
					counter = i+1;
					out.println("<tr><th rowspan=\"4\" ></th><td colspan=\"2\">"+counter+". <b>Flag.</b>");
					for (Flag flag : Flag.valuesAsList()) {
						out.print("<input type=\"radio\" name=\"flag_"+prop.field()+i+"\" value=\""+prop.field()+"\""+faUtil.flagChecked(pr, flag) +">"+flag.title());
					}
					out.print("</td></tr>");
					out.println("<tr><td>");
					out.print("<input type=\"radio\" name=\"act_"+prop.field()+i+"\" value=\""+ProtectedAccess.LOCATION.field()+"\""+faUtil.actChecked(pr, ProtectedAccess.LOCATION) +">"+ProtectedAccess.LOCATION.restriction());
					out.print(": (x1:x2:y1:y2)</td>");
					out.print("<td><input type=\"text\" name=\"loc_"+prop.field()+i+"\" value=\""+faUtil.locValue(pr)+"\"><br>");
					out.print("</td></tr>");
					out.println("<tr><td>");
					out.print("<input type=\"radio\" name=\"act_"+prop.field()+i+"\" value=\""+ProtectedAccess.AP.field()+"\""+faUtil.actChecked(pr, ProtectedAccess.AP) +">"+ProtectedAccess.AP.restriction());
					out.print(": (AP_MAC)</td>");
					out.print("<td><input type=\"text\" name=\"ap_"+prop.field()+i+"\" value=\""+faUtil.apValue(pr)+"\"><br>");
					out.print("</td></tr>");
					out.println("<tr><td>");
				    out.print("<input type=\"radio\" name=\"act_"+prop.field()+i+"\" value=\""+ProtectedAccess.CLIENT.field()+"\""+faUtil.actChecked(pr, ProtectedAccess.CLIENT) +">"+ProtectedAccess.CLIENT.restriction());
					out.print(": (client_ip:subnet_mask)</td>");
					out.print("<td><input type=\"text\" name=\"cl_"+prop.field()+i+"\" value=\""+faUtil.clValue(pr)+"\"><br>");
					out.print("</td></tr>");
					
				}
				
				//ADD NEW

					out.println("<tr ><th rowspan=\"4\"></th><td colspan=\"2\"><b>+add+</b> <b>Flag.</b>");
					for (Flag flag : Flag.valuesAsList()) {
						out.print("<input type=\"radio\" name=\"flag_"+prop.field()+"new\" value=\""+prop.field()+"\""+faUtil.flagChecked(null, flag) +">"+flag.title());
					}
					out.print("</td></tr>");
					out.println("<tr><td>");
					out.print("<input type=\"radio\" name=\"act_"+prop.field()+"new\" value=\""+ProtectedAccess.LOCATION.field()+"\">"+ProtectedAccess.LOCATION.restriction());
					out.print(": (x1:x2:y1:y2)</td>");
					out.print("<td><input type=\"text\" name=\"loc_"+prop.field()+"new\" value=\"\"><br>");
					out.print("</td></tr>");
					out.println("<tr><td>");
					out.print("<input type=\"radio\" name=\"act_"+prop.field()+"new\" value=\""+ProtectedAccess.AP.field()+"\">"+ProtectedAccess.AP.restriction());
					out.print(": (AP_MAC)</td>");
					out.print("<td><input type=\"text\" name=\"ap_"+prop.field()+"new\" value=\"\"><br>");
					out.print("</td></tr>");
					out.println("<tr><td>");
				    out.print("<input type=\"radio\" name=\"act_"+prop.field()+"new\" value=\""+ProtectedAccess.CLIENT.field()+"\">"+ProtectedAccess.CLIENT.restriction());
					out.print(": (client_ip:subnet_mask)</td>");
					out.print("<td><input type=\"text\" name=\"cl_"+prop.field()+"new\" value=\"\"><br>");
					out.print("</td></tr>");
					out.println("<tr><td colspan=\"4\" valign=\"top\" align=\"center\"><INPUT TYPE=\"submit\" VALUE=\"Add rule!\"></td></tr>");
					out.print("</tbody>");
			}
		   
		    out.println("</table><INPUT TYPE=\"submit\" VALUE=\"Update settings!\">");
		    out.println("</FORM>");
	        out.println("<hr/>");
			
		
		} else {
			out.println("<h2>Access denied!</h2>");
			out.println("You are accessing this from external device. To proceed please use local access.");
		}
		out.print("<br/><br/><div id=\"footer\"><center><b>OM project for internet services</b> 2009<br>Darja Krushevskaja &amp;for more information: darja@cs</center></div>");
		out.println("</body>");
		out.println("</html>");

		out.close();
	}
			
}